package com.kgc.skconsumer.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kgc.basic.util.PageInfo;
import com.kgc.basic.util.ResponseMsg;
import com.kgc.collection.pojo.SalesCollection;
import com.kgc.skconsumer.feign.CwOutStoreFeign;
import com.kgc.skconsumer.feign.CwWorkFlowFeign;
import com.kgc.skconsumer.feign.SalesCollectionFeign;
import com.kgc.store.pojo.OutStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/SalesCollectionController")
public class SalesCollectionController {

        private Logger logger = LoggerFactory.getLogger(SalesCollectionController.class);

        @Autowired
        private SalesCollectionFeign salesCollectionFeign;

        @Autowired
        private CwWorkFlowFeign cwWorkFlowFeign;

        @Autowired
        private CwOutStoreFeign cwOutStoreFeign;

        @RequestMapping("/selectSalesCollectionByPage")
        public ResponseMsg selectSalesCollectionByPage(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  selectSalesCollectionByPage params {}",params.toString());
            ResponseMsg responseMsg = salesCollectionFeign.selectSalesCollectionByPage(params);
            logger.debug("SalesCollectionController  selectSalesCollectionByPage responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/insertSalesCollection")
        public  ResponseMsg insertSalesCollection(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  insertSalesCollection params {}",params.toString());
            ResponseMsg responseMsg = salesCollectionFeign.insertSalesCollection(params);
            ObjectMapper mapper = new ObjectMapper();
            SalesCollection salesCollection = mapper.convertValue(params.get("salesCollection"), SalesCollection.class);
            Map<String,Object> variables = new HashMap<>();
            variables.put("code",salesCollection.getDocCode());//单据编号
            variables.put("type",salesCollection.getTypeId());//流程类型
            //创建一个流程实例
            cwWorkFlowFeign.startProcess(variables);
            logger.debug("SalesCollectionController  insertSalesCollection responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/selectSalesCollectionDetail")
        public  ResponseMsg selectSalesCollectionDetail(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  selectSalesCollectionDetail params {}",params.toString());
            ResponseMsg responseMsg = salesCollectionFeign.selectSalesCollectionDetail(params);
            logger.debug("SalesCollectionController  selectSalesCollectionDetail responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/selectSalesCollectionByCode")
        public ResponseMsg selectSalesCollectionByCode(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  selectSalesCollectionByCode params {}",params.toString());
            ResponseMsg responseMsg=salesCollectionFeign.selectSalesCollectionByCode(params);
            logger.debug("SalesCollectionController  selectSalesCollectionByCode responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/updateSalesCollection")
        public  ResponseMsg updateSalesCollection(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  updateSalesCollection params {}",params.toString());
            ResponseMsg responseMsg=salesCollectionFeign.updateSalesCollection(params);
            logger.debug("SalesCollectionController  updateSalesCollection responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/deleteSalesCollection")
        public  ResponseMsg deleteSalesCollection(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  deleteSalesCollection params {}",params.toString());
            ResponseMsg responseMsg=salesCollectionFeign.deleteSalesCollection(params);
            logger.debug("SalesCollectionController  deleteSalesCollection responseMsg {}",responseMsg.toString());
            return responseMsg;
        }

        @RequestMapping("/checkSalesCollection")
        public  ResponseMsg checkSalesCollection(@RequestBody Map<String, Object> params) {
            logger.info("SalesCollectionController  checkSalesCollection params {}",params.toString());
            ResponseMsg responseMsg = new ResponseMsg();
            Map<String,Object> variables = new HashMap<>();
            variables.put("code",(String) params.get("docCode"));//单据编号
            variables.put("checkManId",(Integer) params.get("checkManId"));//审批人
            variables.put("checkManName",(String) params.get("checkManName"));//审批人
            variables.put("checkComment",(String) params.get("checkComment"));//审批意见
            variables.put("checkDate",new Date());//审批时间
            variables.put("checkRes",(boolean)params.get("checkRes"));//审批结果
            com.kgc.activiti.util.ResponseMsg msg=  cwWorkFlowFeign.competeTask(variables);
            //开始单据流转
            //先拿到本对象和源单对象，对比收款的金额，
            variables.put("docCode", params.get("docCode"));
            ObjectMapper objectMapper = new ObjectMapper();
            SalesCollection salesCollection = objectMapper.convertValue(salesCollectionFeign.selectSalesCollectionByCode(variables).getData(), SalesCollection.class);
            //拿到所有有同样源单号的集合
            variables.put("pageNo",1);
            variables.put("pageSize",50);
            Map<String,Object> newMap=new HashMap<>();
            newMap.put("sourceSheet",salesCollection.getSourceSheet());
            newMap.put("pageNo",1);
            newMap.put("pageSize",50);
            Map<String, Object> pageData = (Map<String, Object>) salesCollectionFeign.selectSalesCollectionByPage(newMap).getData();

            //List<LinkedHashMap> → List<SalesCollection>
            List<Map<String, Object>> rawList = (List<Map<String, Object>>) pageData.get("list");
            logger.debug("查看同源单集合{}",rawList.toString());
            List<SalesCollection> salesCollectionList = rawList.stream()
                    .map(item -> objectMapper.convertValue(item, SalesCollection.class))
                    .collect(Collectors.toList());

            // 5. 获取源单信息
            Map<String, Object> variables1 = new HashMap<>();
            variables1.put("code", salesCollection.getSourceSheet());
            variables1.put("typeId", 6);
            Map<String, Object> sourceData = (Map<String, Object>) cwOutStoreFeign.getOutStoreList(variables1).getData();

            // LinkedHashMap → OutStore
            List<Map<String, Object>> sourceList = (List<Map<String, Object>>) sourceData.get("list");
            OutStore outStore = objectMapper.convertValue(sourceList.get(0), OutStore.class);


            //获取源单总金额
            outStore.getOutStoreSumPrice();
            //一次收款金额
            salesCollection.getCollectionAmount();

            BigDecimal totalReceived = salesCollectionList.stream().filter(c -> c.getStatus()==3)
                    .map(c -> new BigDecimal(c.getCollectionAmount().toString()))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal sourceTotal = new BigDecimal(outStore.getOutStoreSumPrice().toString());

            if (totalReceived.compareTo(sourceTotal) >= 0) {
                cwOutStoreFeign.changeStatus(outStore.getCode(),11);

                // 7.2 作废其他未审核的收款单
                salesCollectionList.stream()
                        .filter(c -> c.getStatus() >= 0 &&c.getStatus() <3 && !c.getDocCode().equals(salesCollection.getDocCode()))
                        .forEach(c -> {
                            Map<String,Object> variables2 = new HashMap<>();
                            variables2.put("docCode",c.getDocCode());
                            variables2.put("status",12);
                            salesCollectionFeign.checkSalesCollection(variables2);
                        });

                logger.info("源单 {} 已全额收款并关闭", outStore.getCode());
            } else if (totalReceived.compareTo(BigDecimal.ZERO) > 0) {
                cwOutStoreFeign.changeStatus(outStore.getCode(),6);
                logger.info("源单 {} 已部分收款", outStore.getCode());
            }

            responseMsg.setCode(msg.getCode());
            responseMsg.setMsg(msg.getMsg());
            logger.debug("SalesCollectionController  checkSalesCollection responseMsg {}",responseMsg.toString());
            return responseMsg;
        }
}
